package com.hmdp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hmdp.constant.GlobalConstant;
import com.hmdp.entity.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public Result queryTypeList() {
        List<String> range = redisTemplate.opsForList().range(GlobalConstant.SHOP_TYPE_LIST, 0, -1);
        if(!range.isEmpty())
        {
            List<ShopType> typeList = range.stream().map(item -> {
                JSONObject jsonObject = JSON.parseObject(item);
                return jsonObject.toJavaObject(ShopType.class);
            }).collect(Collectors.toList());
            return Result.ok(typeList);
        }
        List<ShopType> typeList = this
                .query().orderByAsc("sort").list();
        List<String> collect = typeList.stream().map(item -> JSON.toJSONString(item)).collect(Collectors.toList());

        redisTemplate.opsForList().rightPushAll(GlobalConstant.SHOP_TYPE_LIST,collect);
        return Result.ok(typeList);
    }
}
